package Demo1;

import java.util.*;

public class Solution {
      public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
     }
  }

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        creatChildTree(root, stringBuilder);
        return stringBuilder.toString();
    }

    private void creatChildTree(TreeNode root, StringBuilder stringBuilder){
        if (root == null){
            return;
        }

        stringBuilder.append(root.val);

        if (root.left != null){
            stringBuilder.append("(");
            creatChildTree(root.left, stringBuilder);
            stringBuilder.append(")");
        }else{
            if (root.right == null){
                return;
            }else{
                stringBuilder.append("()");
            }

        }

        if (root.right != null){
            stringBuilder.append("(");
            creatChildTree(root.right, stringBuilder);
            stringBuilder.append(")");
        }else{
            if (root.right == null){
                return;
            }else{
                stringBuilder.append("()");
            }
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }

        Stack<TreeNode> stack = new Stack<>();
        while (root != null){
            stack.push(root);
            root = root.left;
        }

        while (!stack.isEmpty()){
            TreeNode top = stack.pop();
            ret.add(top.val);

            if (top.right != null){
                ret.add(top.right.val);
            }
        }

        return ret;
    }

    public int[] smallestK(int[] arr, int k) {
        int[] vec = new int[k];
        if (k == 0) { // 排除 0 的情况
            return vec;
        }
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
            public int compare(Integer num1, Integer num2) {
                return num2 - num1;
            }
        });
        for (int i = 0; i < k; ++i) {
            queue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; ++i) {
            if (queue.peek() > arr[i]) {
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; ++i) {
            vec[i] = queue.poll();
        }
        return vec;
    }
}

class Main{
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] ret = test.smallestK(new int[]{1,3,5,7,2,4,6,8}, 4);
    }
}
